package com.icloud.auth.boot.listener;

import com.icloud.auth.boot.domain.SecurityUser;
import com.icloud.common.cache.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

@Component
public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {
    @Autowired
    private TokenUtil tokenUtil;
    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        Authentication authentication = event.getAuthentication();
        Object principal = authentication.getPrincipal();
        if(principal instanceof SecurityUser){
            SecurityUser securityUser = (SecurityUser) principal;
            String clientId =  securityUser.getClientId();
            Long id = securityUser.getId();
            if(StringUtils.isNotBlank(clientId) && id!=null){
                String hashKey = clientId+"_"+id;
                tokenUtil.cacheAccessToken(hashKey, id);
            }
        }
    }
}
